<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑用户</title>
    <style>
        body { font-family: Arial, sans-serif; }
        .container { width: 300px; margin: 50px auto; }
        .form-group { margin-bottom: 10px; }
        label { display: block; margin-bottom: 5px; }
        input { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
        button { padding: 10px 20px; cursor: pointer; background-color: #28a745; color: white; border: none; border-radius: 4px; }
    </style>
</head>
<body>
<div class="container">
    <h2>编辑用户</h2>
    <form id="editUserForm">
        <div class="form-group">
            <label for="editEmail">邮箱:</label>
            <input type="email" id="editEmail" name="editEmail" required>
        </div>
        <div class="form-group">
            <label for="editName">姓名:</label>
            <input type="text" id="editName" name="editName" required>
        </div>
        <div class="form-group">
            <label for="editContactInfo">联系方式:</label>
            <input type="text" id="editContactInfo" name="editContactInfo" required>
        </div>
        <div class="form-group">
            <label for="editrole">身份:</label>
            <input type="text" id="editrole" name="editrole" required>
        </div>
        <div class="form-group">
            <label for="editPassword">密码:</label>
            <input type="password" id="editPassword" name="editPassword" required>
        </div>
        <input type="hidden" id="editUserId" name="editUserId"> <!-- 隐藏字段用于存储用户ID -->
        <div class="form-group">
            <button type="button" onclick="updateUser()">更新用户</button>
            <button type="button" onclick="window.history.back()">取消</button>
        </div>
    </form>
    <button onclick="toggleNewAddressForm()" id="newAddressButton">新建收货地址</button>
    <form id="new-address-form" style="display:none;">
        <div class="form-group">
            <label for="recipientName">收货人姓名:</label>
            <input type="text" id="recipientName" name="recipientName" required>
        </div>
        <div class="form-group">
            <label for="phone">电话:</label>
            <input type="text" id="phone" name="phone" required>
        </div>
        <div class="form-group">
            <label for="address">地址:</label>
            <input type="text" id="address" name="address" required>
        </div>
        <div class="form-group">
            <button type="button" onclick="saveNewAddress()">保存地址</button>
            <button type="button" onclick="toggleNewAddressForm()">取消</button>
        </div>
    </form>
    <div id="addresses"></div>
</div>

<script>
    // 获取 URL 参数的函数
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
        var results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    document.addEventListener('DOMContentLoaded', function() {
        var userId = getParameterByName('id');
        if (userId) {
            populateEditUserFields(userId);
            fetchShippingAddresses(userId); // 获取收货地址列表
        }
    });

    // 根据用户ID填充表单字段
    function populateEditUserFields(userId) {
        if (!userId) return;
        fetch(`/api/users/${userId}`, {
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(user => {
                console.log(user); // 打印出用户数据，检查数据是否正确
                if (user && user.userID) {
                    document.getElementById('editEmail').value = user.email;
                    document.getElementById('editContactInfo').value = user.contactInfo || '';
                    document.getElementById('editPassword').value = user.password || '';
                    document.getElementById('editrole').value = user.role || '';
                    document.getElementById('editName').value = user.name || ''; // 填充姓名字段
                    document.getElementById('editUserId').value = user.userID; // 设置隐藏字段的值
                } else {
                    alert('未找到该用户ID对应的用户');
                    document.getElementById('editEmail').value = '';
                    document.getElementById('editContactInfo').value = '';
                    document.getElementById('editrole').value =  '';
                    document.getElementById('editPassword').value = '';
                    document.getElementById('editName').value = '';
                    document.getElementById('editUserId').value = '';
                }
            })
            .catch(error => {
                console.error('Error fetching user:', error);
                alert('无法加载用户信息: ' + error.message);
            });
    }

    // 更新用户信息
    function updateUser() {
        const email = document.getElementById('editEmail').value;
        const contactInfo = document.getElementById('editContactInfo').value;
        const password = document.getElementById('editPassword').value;
        const role = document.getElementById('editrole').value;
        const name = document.getElementById('editName').value; // 获取姓名字段的值
        const userId = document.getElementById('editUserId').value;
        if (!email || !contactInfo || !password || !name || !userId ) {
            alert('请填写所有字段');
            return;
        }

        fetch(`/api/users/${userId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email, contactInfo, password, name }),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                console.log('Update successful:', data);
                alert('用户更新成功');
                window.history.back(); // 返回上一页
            })
            .catch(error => {
                console.error('Error updating user:', error);
                alert('用户更新失败: ' + error.message);
            });
    }

    window.toggleNewAddressForm = function() {
        const newAddressForm = document.getElementById("new-address-form");
        if (newAddressForm) {
            newAddressForm.style.display = newAddressForm.style.display === 'none' ? 'block' : 'none';
        } else {
            const formHtml = `
                <form id="new-address-form" style="display:none;">
                    <h3>新建收货地址</h3>
                    <label for="recipientName">收货人姓名:</label>
                    <input type="text" id="recipientName" name="recipientName" required><br><br>
                    <label for="phone">电话:</label>
                    <input type="text" id="phone" name="phone" required><br><br>
                    <label for="address">地址:</label>
                    <input type="text" id="address" name="address" required><br><br>
                    <button type="button" onclick="saveNewAddress()">保存地址</button>
                    <button type="button" onclick="toggleNewAddressForm()">取消</button>
                </form>
            `;
            document.getElementById("container").insertAdjacentHTML('beforeend', formHtml);
        }
    };

    window.saveNewAddress = function() {
        const userId = document.getElementById('editUserId').value; // 获取当前页面的用户ID
        if (!userId) {
            alert('用户ID未找到');
            return;
        }

        const recipientName = document.getElementById("recipientName").value;
        const phone = document.getElementById("phone").value;
        const address = document.getElementById("address").value;
        getUserById(userId).then(user => {
            const shippingAddress = {
                recipientName: recipientName,
                phone: phone,
                address: address,
                user: user // 设置关联的用户
            };

            // 发送 POST 请求以新建地址
            fetch(`/api/shipping-addresses`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(shippingAddress), // 传递整个 shippingAddress 对象
                credentials: 'include'
            })
                .then(response => {
                    if (response.ok) {
                        alert('地址保存成功');
                        fetchShippingAddresses(userId);
                        toggleNewAddressForm(); // 隐藏表单
                    } else {
                        alert('地址保存失败');
                    }
                })
                .catch(error => {
                    console.error('Error saving address:', error);
                    alert('保存地址时出错');
                });
        });
    };

    function fetchShippingAddresses(userId) {
        fetch(`/api/shipping-addresses/user/${userId}`, {
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                const addressesDiv = document.getElementById("addresses");
                if (data && data.length > 0) {
                    addressesDiv.innerHTML = data.map(address => `
        <div>
            <p>${address.recipientName}, ${address.phone}, ${address.address}</p>
            <button onclick="editAddress(${address.id})">编辑</button>
            <button onclick="deleteAddress(${address.id})">删除</button>
        </div>
    `).join('');
                } else {
                    addressesDiv.innerHTML = "<p>暂无收货地址</p>";
                }
            })
            .catch(error => {
                console.error('Error fetching addresses:', error);
                document.getElementById("addresses").textContent = "获取收货地址失败：" + error.message;
            });
    }

    function createEditAddressForm() {
        const editAddressForm = document.getElementById("edit-address-form");
        if (!editAddressForm) {
            const formHtml = `
<form id="edit-address-form" style="display:none; margin-top:20px;">
    <h3>编辑收货地址</h3>
    <label for="recipientName">收货人姓名:</label>
    <input type="text" id="recipientName" name="recipientName" required><br><br>
    <label for="phone">电话:</label>
    <input type="text" id="phone" name="phone" required><br><br>
    <label for="address">地址:</label>
    <input type="text" id="address" name="address" required><br><br>
    <input type="hidden" id="addressId" name="addressId">
    <button type="button" onclick="saveEditedAddress()">保存地址</button>
    <button type="button" onclick="toggleEditAddressForm()">取消</button>
</form>
`;
            document.body.insertAdjacentHTML('beforeend', formHtml);
        } else {
            console.log("Edit address form already exists");
        }
    }

    window.toggleEditAddressForm = function() {
        const editAddressForm = document.getElementById("edit-address-form");
        if (editAddressForm) {
            editAddressForm.style.display = editAddressForm.style.display === 'none' ? 'block' : 'none';
        } else {
            console.error("Edit address form does not exist");
        }
    };

    window.editAddress = function(addressId) {
        createEditAddressForm();
        const recipientNameInput = document.getElementById("recipientName");
        const phoneInput = document.getElementById("phone");
        const addressInput = document.getElementById("address");
        const addressIdInput = document.getElementById("addressId");

        fetch(`/api/shipping-addresses/${addressId}`, {
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(address => {
                if (address) {
                    recipientNameInput.value = address.recipientName;
                    phoneInput.value = address.phone;
                    addressInput.value = address.address;
                    addressIdInput.value = address.id;
                    document.getElementById("edit-address-form").style.display = 'block';
                } else {
                    alert('地址加载失败');
                }
            })
            .catch(error => {
                console.error('Error fetching address:', error);
                alert('加载地址时出错');
            });
    };

    window.saveEditedAddress = function() {
        const addressId = document.getElementById("addressId").value;
        const recipientName = document.getElementById("recipientName").value;
        const phone = document.getElementById("phone").value;
        const address = document.getElementById("address").value;
        const userId = document.getElementById('editUserId').value;

        fetch(`/api/shipping-addresses/${addressId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                recipientName: recipientName,
                phone: phone,
                address: address,
                userId: userId
            }),
            credentials: 'include'
        })
            .then(response => {
                if (response.ok) {
                    alert('地址更新成功');
                    fetchShippingAddresses(userId);
                    toggleEditAddressForm();
                } else {
                    alert('地址更新失败');
                }
            })
            .catch(error => {
                console.error('Error updating address:', error);
                alert('更新地址时出错');
            });
    };

    function getUserID() {
        return fetch('/api/get-user-id', {
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to fetch user ID');
                }
                return response.text();
            })
            .catch(error => {
                console.error('Error fetching user ID:', error);
                alert('无法获取用户ID');
                return Promise.resolve("not_logged_in");
            });
    }

    function getUserById(userId) {
        return fetch(`/api/users/get-user-info?userId=${userId}`, {
            credentials: 'include'
        })
            .then(response => response.json());
    }
</script> </body> </html>